$(function() {

    var ismedia = 'img';
    var str_cont = '';
    var str_folder = 'img';
    
    $('.addphoto ').live('click', function(){

        $.ajax({
            type: 'POST',
            url: base_url+'core/mediaeditor',
            dataType: 'json',
            success: function(data){



                $("#mediamodaleditor").modal({

                    opacity: 70,
                    containerCss:{
                        background: '#FFFFFF',
                        border: 0,
                        padding: 0,
                        width: 860,
                        height: 552
                    },
                    overlayCss:{
                        background: '#000000'
                    },
                    position: ["7%",''] ,
                    onOpen: function (dialog) {
                        dialog.overlay.fadeIn('slow', function () {
                            dialog.data.hide();
                            dialog.container.fadeIn('slow', function () {
                                dialog.data.slideDown('slow',function(){

                                    $('.zmodalClose').fadeIn('fast').delay(118000);

                                    $('.simplemodal-container').css('height','inherit')

                                    $("#mediamodaleditor").html(data.html);


                                    var folder_url_img = 'mediagallery/img/';
                                    var folder_url_vid = 'mediagallery/videos/';

                                    var folder_url = folder_url_img;

                                    ismedia = 'img';
                                    
                                    var uploader = new plupload.Uploader({

                                        runtimes: 'flash',
                                        flash_swf_url: base_url+'assets/js/_plugins/plupload/plupload.flash.swf',
                                        browse_button: 'pickfiles',
                                        container: 'uploader',
                                        url: base_url+'assets/js/_plugins/plupload/upload.php',
                                        multipart : true,
                                        multipart_params: { 'datafield': folder_url },
                                        unique_names: true 

                                    });

                                    if(ismedia=='img'){

                                        uploader.settings.multipart_params.datafield = folder_url_img;    

                                    }else if(ismedia=='vid'){

                                        uploader.settings.multipart_params.datafield = folder_url_vid;

                                    }

                                    console.log(uploader.settings.multipart_params.datafield)


                                    uploader.init();

                                    uploader.bind('FilesAdded', function(up, files) {        
                                        // loop through the files array
                                        for (var i in files) {            
                                            document.getElementById('filelist').innerHTML += '<div id="' + files[i].id + '">' + files[i].name + ' (' + plupload.formatSize(files[i].size) + ') <b></b></div>';            
                                        }
                                        console.log(uploader.settings.multipart_params.datafield)  
                                    });

                                    uploader.bind('UploadProgress', function(up, file) {        
                                        document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";        
                                    });

                                    uploader.bind('Error', function(up, args) {        
                                        alert(args.code + ': ' + args.message);        
                                    });

                                    document.getElementById('uploadfiles').onclick = function() {         
                                        uploader.start();         
                                    };

                                    uploader.bind('FileUploaded', function(up, file, info) {
                                        //console.log("uploaded");

                                        if( (uploader.total.uploaded + 1) == uploader.files.length) {
                                            //window.location = 'uploaded.php?file=' + encodeURIComponent(File.name);
                                            //console.log("uploaded complete");
                                        };

                                        //console.log('[FileUploaded] up:', up,' File:', file, "Info:", info);

                                        fname = file.target_name;

                                        //console.log('encodeURIComponent: '+fname)



                                        switch(ismedia){
                                            case 'img':
                                                str_cont = '#imgholder .rowholder';
                                                str_folder = 'img';
                                                break;
                                            case 'vid':
                                                str_cont = '#videoholder .rowholder';
                                                str_folder = 'videos'; 
                                                break;
                                        }

                                        var html  = $('<div class="row clearfix">'+
                                        '<div class="display"><img width="70" src="http://localhost/dan-portal-cms/assets/mediagallery/'+str_folder+'/'+fname+'" /></div>'+
                                        '<div class="path">'+fname+'</div>'+
                                        '<div class="action">'+
                                        '<a class="change btn" href="javascript:">Promjeni</a>'+
                                        '<a class="delete btn" href="javascript:">Briši</a>'+
                                        '</div>'+
                                        '</div>');

                                        cnt_row = $(str_cont +' .row').length;

                                        if(cnt_row > 0){
                                            $(str_cont).append(html); 
                                        }else{
                                            $(str_cont).html(html) 
                                        }                                           


                                        $(str_cont).animate({scrollTop: $(str_cont).offset().top});

                                    });

                                    /*ID TABS WITH SELECTORS */ 
                                    jQuery('#simpletabs ul').idTabs();

                                    $('#simpletabs > ul > li > a').click(function(){

                                        $(this).parent().parent().find(".on").removeClass('on');
                                        $(this).closest('li').addClass('on');

                                    });

                                    $('#img_a').click( function(){

                                        ismedia = 'img';
                                        uploader.settings.multipart_params.datafield = folder_url_img;
                                        console.log('trace:'+uploader.settings.multipart_params.datafield) 
                                    })

                                    $('#vid_a').click( function(){

                                        ismedia = 'vid';
                                        uploader.settings.multipart_params.datafield = folder_url_vid;
                                        console.log('trace:'+uploader.settings.multipart_params.datafield) 
                                    }) 



                                });
                            });
                        });

                    },
                    onClose: function (dialog) {
                        dialog.data.fadeOut('slow', function () {
                            dialog.container.slideUp('slow', function () {
                                dialog.overlay.fadeOut('slow', function () {
                                    $.modal.close(); // must call this!
                                });
                            });
                        });
                    },
                    closeClass: 'zmodalClose'
                });
                $('.zmodalClose').css({
                    'margin-right':'0',
                    'margin-top':'0',
                    'display':'none'
                });


            },
            error:function(data){alert("Error: " + data);}
        });
        return false;

    })

    //$('.addphoto ').trigger('click');

    $('.row').live('click', function(){

        $.modal.close();

        switch(ismedia){

            case 'img':

                $('.art_intro .img').html('<img src="'+base_url+'assets/mediagallery/img/'+$(this).children(".path").html()+'" />')

                $('#_filepath').val($(this).children(".path").html());
                $('#_type').val('img');

                break;

            case 'vid':

                $('.art_intro .img').html('<img src="'+base_url+'assets/mediagallery/videos/'+$(this).children(".path").html()+'" />')

                $('#_filepath').val($(this).children(".path").html());
                $('#_type').val('video');

                break;
        }




    })


    $('#form_submit').live('click', function(){

        $("#newartform").trigger('submit');

    })    

});

                            